//app.js
App({
  onShow: function () {
    // 判断是否获取useInfo
    try {
      let userInfo = wx.getStorageSync('userInfo')
      if (userInfo == '' || userInfo == undefined || !userInfo) {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      } else {
        wx.checkSession({
          success: () => {
            // do sth
          },
          fail: () => {
            // do sth
            wx.login({
              success: (res) => {
                if (res.code) {
                  // code 发送到后端
                  this.get('user/login',{code: res.code})
                    .then()
                }
              }
            })
          }
        })
      }
    } catch (e) {
      console.log(e)
      wx.redirectTo({
        url: '/pages/index/index',
      })
    }
    let result = wx.getSystemInfoSync()
    this.globalData.screenHeight = result.screenHeight
    this.globalData.screenWidth = result.screenWidth
    this.globalData.windowHeight = result.windowHeight
    this.globalData.windowWidth = result.windowWidth
  },
  globalData: {
    API_URL: 'https://minapp.510link.com/'
  },

  /**
   * 
   * get
   * @params url
   * @params data
   * @return promise 
   */
  get: function(url, data, isLoading = false) {
    if (isLoading) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    }
    return new Promise((resolve, reject) => {
      this.request(url, data, 'GET')
        .then(res => {
          resolve(res)
          if (isLoading) {
            wx.hideLoading()
          }
        })
        .catch(res => {
          reject(res)
          if (isLoading) {
            wx.hideLoading()
          }
        })
    })
  },

  /**
   * 
   * post
   * @params url
   * @params data
   * @return promise 
   */
  post: function(url, data, isLoading = false) {
    return new Promist((resolve, reject) => {
      this.request(url, data, 'POST')
        .then(res => {
          resolve(res)
          if (isLoading) {
            wx.hideLoading()
          }
        })
        .catch(res => {
          reject(res)
          if (isLoading) {
            wx.hideLoading()
          }
        })
    })
  },

  request:function (url, data, method) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.globalData.API_URL + url,
        data: data,
        method: method,
        success: (res) => {
          if (res.data.code === 2000) {
            resolve(res.data.data)
          } else {
            reject(res.data.msg)
          }
        },
        fail: (res) => {
          this.toast('网络异常')
        }
      })
    })
  },

  toast: function(title, duration = 2000, mask = false) {
    wx.showToast({
      title: title,
      icon: 'none',
      mask: mask,
      duration: duration
    })
  },
  imgs: function (urls, current) {
    wx.previewImage({
      urls: urls,
      current: current
    })
  }
})